package com.sljy.hzk.ui.task;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.sljy.hzk.R;
import com.sljy.hzk.annotation.ActivityInfo;
import com.sljy.hzk.base.BaseActivity;
import com.sljy.hzk.base.UserInfo;
import com.sljy.hzk.entity.TaskBodyEntity;
import com.sljy.hzk.entity.TaskDetailEntity;
import com.sljy.hzk.entity.TaskEntity;
import com.sljy.hzk.entity.TaskMainEntity;
import com.sljy.hzk.entity.TaskSmEntity;
import com.sljy.hzk.entity.UserEntity;
import com.sljy.hzk.net.BaseCallBack;
import com.sljy.hzk.net.CommonResult;
import com.sljy.hzk.net.HttpHeper;
import com.sljy.hzk.net.service.TaskService;
import com.sljy.hzk.room.AppDataBase;
import com.sljy.hzk.room.dao.TaskBodyDao;
import com.sljy.hzk.room.dao.TaskDao;
import com.sljy.hzk.ui.LoginActivity;
import com.sljy.hzk.ui.QrCodeActivity;
import com.sljy.hzk.ui.fragment.TaskListFragment;
import com.sljy.hzk.util.EventListenerManager;
import com.sljy.hzk.util.NetWorkUtils;
import com.sljy.hzk.util.NotificationService;
import com.sljy.hzk.util.TimeUtils;
import com.sljy.hzk.view.adapter.LoginItemMyAdapter;
import com.sljy.hzk.view.adapter.TaskItemAdapter;
import com.tkk.api.RxEventProcessor;
import com.tkk.api.ThreadType;
import com.tkk.api.annotation.Recipient;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindColor;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@ActivityInfo(layout = R.layout.activity_task_main,isShowActionBar = true, title = "我的任务", rightIcRes = R.drawable.homepage)
public class TaskMainActivity extends BaseActivity {
    @BindView(R.id.tv_yesterday)
    TextView tvYesterday;
    @BindView(R.id.tv_calendar)
    TextView tvCalendar;
    @BindView(R.id.tv_tomorrow)
    TextView tvTomorrow;
    @BindView(R.id.refresh)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.refresh_lv)
    ListView listViewAdapter;
    @BindColor(R.color.color_white)
    int tvTomorrowColor;
    @BindColor(R.color.color_text_666)
    int tvTomorrowNotColor;
    @BindView(R.id.date_bg)
    RelativeLayout date_bg;
    @BindView(R.id.clearAll)
    RelativeLayout  clearAll;
    boolean isCanGoTomorrow = false;
    private List<TaskListFragment> fragments = new ArrayList<>();
    private Date nowDate = TimeUtils.getNowDate();//今天日期
    private Date choseDate = nowDate;//当前选择的日期
    UserEntity user;
    private List<TaskEntity> over = new LinkedList<>();
    private List<TaskEntity> noFinish = new LinkedList<>();
    TextView tvNumNoFinsh;
    TextView tvNumOver;
    private List<TaskEntity> finish = new LinkedList<>();
    TaskBodyDao taskBodyDao;
    TaskDao taskDao;
    private int pageIndex = 0;
    private boolean isFinsh = false;

    @Override
    protected void init() {
        RxEventProcessor.get().bind(this);
        clearAll.setVisibility(View.GONE);
        user = UserInfo.getUserInfo();
        taskBodyDao =  AppDataBase.getInstance().getTaskBodyDao();
        taskDao = AppDataBase.getInstance().getTaskDao();
        tvCalendar.setText(TimeUtils.getNowNyr());
        tvCalendar.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("nowDate", TimeUtils.dateToStr(nowDate));
                intent.setClass(TaskMainActivity.this, Task_DateActivity.class);
                startActivity(intent);
            }
        });
        //tvTomorrow.setTextColor(tvTomorrowNotColor);
        fragments.add(TaskListFragment.get(TaskListFragment.TASK_UNFINSH, noFinish));
        fragments.add(TaskListFragment.get(TaskListFragment.TASK_TIME_OVER, over));
        fragments.add(TaskListFragment.get(TaskListFragment.TASK_FINSHED, finish));
        getByDate(nowDate);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener(){
            @Override
            public void onRefresh() {
                swipeRefreshLayout.setRefreshing(false);
                onRefreshToast();
                getByDate(nowDate);
            }
        });
    }

    private void rightClick() {
        Intent intent = new Intent();
        intent.putExtra("workId", doId);
        intent.putExtra("date",  TimeUtils.dateToStr(nowDate));
        intent.setClass(this,QrCodeActivity.class);
        startActivity(intent);
//        new IntentIntegrator(this)
//                .setCaptureActivity(QrCodeActivity.class)
//                .setPrompt("请对准二维码")
//                .setCameraId(0)
//                .initiateScan();
    }
    //扫码结束解锁成功后直接进入执行界面
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if(result != null) {
            if(result.getContents() != null) {
                String url =  result.getContents();
                url = analysisUrl(url);
//                Gson gson = new Gson();
//                TaskSmEntity taskSmEntity = null;
//                try {
//                    taskSmEntity = gson.fromJson(url, TaskSmEntity.class);
//                }catch (Exception e){
//
//                }
                if (url != null) {
                    //reSort(taskSmEntity.getId());
                    //请求解锁
                    HttpHeper.get().create(TaskService.class)
                            .UnlockTask(Integer.parseInt(url), doId, TimeUtils.dateToStr(nowDate))
                            .enqueue( new Callback<CommonResult<String>>(){
                            @Override
                            public void onResponse(Call<CommonResult<String>> call, Response<CommonResult<String>> response) {
                                if(response.body().getData().equals("1")){
                                    showToast(response.body().getMsg());
                                }else{
                                    showToast(response.body().getMsg());
                                    return;
                                }
                                //如果是点击执行的话，应该直接进入到界面
                                //把本地的缓存修改为解锁
                                boolean isNext = false;
                                for( TaskEntity list : noFinish){
                                    if(list.getWorkPlanId() == doId){
                                        isNext = true;
                                        list.setAppSwitch(1);
                                        break;
                                    }
                                }
                                if(!isNext){
                                    for(TaskEntity list : over){
                                        if(list.getWorkPlanId() == doId){
                                            list.setAppSwitch(1);
                                        }
                                    }
                                }
                                DoTaskCallBack(doId, doIsHaveFromLocal, false,false,false);
                            }
                            @Override
                            public void onFailure(Call<CommonResult<String>> call, Throwable t) {
                                showToast("解锁失败");
                            }
                    });
                }else {
                    showToast("请扫描车间二维码");
                }
                Log.d(TAG, ">>>onActivityResult---" + url);
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    /**
     * 解析扫描得到的url，分解出examId
     * @param url
     */
    private String analysisUrl(String url){
        String examId = null;
        String includeStr = "id";
        String endStr = "parentId";
        if (url.contains(includeStr)){
            int first1=url.indexOf(includeStr);
            int end = url.indexOf(endStr);
            //从索引处到末尾（不包括索引处）
            String substr1=url.substring(first1,end);
            first1=substr1.indexOf(":");
            substr1=substr1.substring(first1+1,substr1.length()-2);
            examId =  substr1;
        }
        return examId;
    }


    /**
     * 通过id重新排序-异步抄作
     * @param id
     */
    private void reSort(int id) {
        MaterialDialog progressDialog =  new MaterialDialog.Builder(this)
                .content("数据获取中")
                .progress(true, 0)
                .cancelable(false)
                .build();
        Observable.just(noFinish,over,finish)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(list-> {
                    int num = 0;
                    for (int i = 0; i < list.size(); i++) {
                        TaskEntity taskEntity = list.get(i);
                        if (taskEntity.getId() == id){
                            list.remove(i);
                            list.add(num,taskEntity);
                            num++;
                        }
                    }
                    return list;
                })
                .doOnSubscribe(disposable -> progressDialog.show())
                .doOnComplete(() -> {
                    progressDialog.dismiss();
                    fragments.get(0).notify(noFinish);
                    fragments.get(1).notify(over);
                    fragments.get(2).notify(finish);
                })
                .doOnError(throwable -> {
                    progressDialog.dismiss();
                    showToast(throwable.getMessage());
                })
                .subscribe()
        ;
    }

    /**
     * 保存-上传成功-任务
     */
    @Recipient(tag = "dataHaveChange")
    public void dataHaveChange() {
        getByDate(nowDate);
    }

    /**
     * 通过日期获取时间
     * @param date
     */
    private void getByDate(Date date) {
        if(!NetWorkUtils.isNetworkConnected(this)){
            //检查是否有本地文件
            List<TaskBodyEntity> taskBodyData = taskBodyDao.getByUserId(user.getUserId());
            if(taskBodyData.size() == 0){
                //没有文件，提示去连接网络
                if(!NetState()){
                    return;
                }
            }else{
                //有文件，调出清单
                Gson gson = new Gson();
                TaskMainEntity taskMainEntity = new TaskMainEntity();
                int num = 0;
                for(TaskBodyEntity task : taskBodyData){
                    List<TaskEntity> list = gson.fromJson(task.getDataJson(),new TypeToken<List<TaskEntity>>(){}.getType());
                    switch (num){
                        case 0:
                            taskMainEntity.setNoFinish(list);
                            break;
                        case 1:
                            taskMainEntity.setOver(list);
                            break;
                        case 2:
                            taskMainEntity.setFinish(list);
                            break;
                    }
                    num++;
                }
                LoadData(date, taskMainEntity);
            }
            return;
        }
        HttpHeper.get().create(TaskService.class)
                .getTaskByDate(user.getCpId(), user.getPId(), TimeUtils.dateToStr(date))
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(getThread())
                .subscribe(new BaseCallBack<TaskMainEntity>(this) {
                    @Override
                    public void onCallBackSuccess(TaskMainEntity data) {
                        LoadData(date, data);
                    }

                    @Override
                    public void onFail(String mes) {
                        showToast(mes);
                    }
                });
    }

    //加载数据
    private void LoadData(Date date, TaskMainEntity data){
        tvCalendar.setText(TimeUtils.dateToStr(date));
        over.clear();
        noFinish.clear();
        finish.clear();
        Intent intent = getIntent();
        int DoId = intent.getIntExtra("type",10);
        List<TaskEntity> l = new ArrayList<TaskEntity>();
        switch (DoId){
            case R.id.focusEffct1:
                setTitle("未完成");
                date_bg.setBackgroundColor(this.getResources().getColor(R.color.color_dcf3ff));
                l.addAll(getList(data.getNoFinish(), true));
                break;
            case R.id.focusEffct3:
                setTitle("已完成");
                date_bg.setBackgroundColor(this.getResources().getColor(R.color.color_f9fef0));
                l.addAll(data.getFinish());
                for( TaskEntity info : l){
                    info.setFlag(2);
                }
                break;
            case R.id.focusEffct2:
                setTitle("逾期");
                date_bg.setBackgroundColor(this.getResources().getColor(R.color.color_fff2d8));
                l.addAll(data.getOver());
                for( TaskEntity info : l){
                    info.setFlag(1);
                }
                break;
            case R.id.focusEffct4:
                setTitle("待上传");
                date_bg.setBackgroundColor(this.getResources().getColor(R.color.color_dcf3ff));
                l.addAll(getList(data.getNoFinish(), false));
                break;
        }
        if(l.size() == 0)
            clearAll.setVisibility(View.VISIBLE);
        BaseAdapter adapter = new TaskItemAdapter(l,TaskMainActivity.this);
        listViewAdapter.setAdapter(adapter);
//
//
//        if (data.getOver() != null) {
//            over.addAll(data.getOver());
//            fragments.get(1).notify(over);
//            if (data.getOver().size() != 0) {
//                tvNumOver.setVisibility(View.VISIBLE);
//                tvNumOver.setText(String.valueOf(over.size()));
//            } else {
//                tvNumOver.setVisibility(View.GONE);
//            }
//        }
//        if (data.getNoFinish() != null) {
//            noFinish.addAll(data.getNoFinish());
//            fragments.get(0).notify(noFinish);
//            if (data.getNoFinish().size() != 0) {
//                tvNumNoFinsh.setVisibility(View.VISIBLE);
//                tvNumNoFinsh.setText(String.valueOf(noFinish.size()));
//            } else {
//                tvNumNoFinsh.setVisibility(View.GONE);
//            }
//        }
//        if (data.getFinish() != null) {
//            finish.addAll(data.getFinish());
//            fragments.get(2).notify(finish);
//        }
        //SaveDataToDao(fragments);
    }

    /**
     * 在未完成中分离未完成的和待上传的
     * */
    private List<TaskEntity> getList (List<TaskEntity> data, boolean isUnfinish){
        List<TaskEntity> list1 = new ArrayList<TaskEntity>();
        List<TaskEntity> list2 = new ArrayList<TaskEntity>();
        for(TaskEntity l : data){
            String s = taskDao.get(l.getWorkPlanId());
            if(s != null && s != "")
                list1.add(l);
            else
                list2.add(l);
        }
        if(isUnfinish)return  list2;
        return list1;
    }

    /**
     * 选择日期
     */

    //@OnClick(R.id.layout_calendar)
    void openCalendar() {
        Calendar ca = Calendar.getInstance();
        DatePickerDialog datePickerDialog = new DatePickerDialog(this, (view, year, month, dayOfMonth) -> {
            view.getDrawingTime();
            long d = TimeUtils.dateDiff(TimeUtils.dateToStr(TimeUtils.getNowDate()),TimeUtils.dateToStr(TimeUtils.getDateByNyr(year, month, dayOfMonth)));
//            if(pageIndex != 0){
//                if(d >-8 & d < 0) haveChoseDate(TimeUtils.getDateByNyr(year, month, dayOfMonth));
//                else showToast("查看失败,只能查看前一周内的任务");
//                return;
//            }
            if(d >-8 & d < 8) haveChoseDate(TimeUtils.getDateByNyr(year, month, dayOfMonth));
            else showToast("查看失败,只能查看前后一周内的任务");
        }, ca.get(Calendar.YEAR), ca.get(Calendar.MONTH), ca.get(Calendar.DAY_OF_MONTH));
        if(pageIndex != 0) datePickerDialog.getDatePicker().setMaxDate(TimeUtils.getNowDate().getTime());
        else datePickerDialog.getDatePicker().setMaxDate(TimeUtils.GetNextWeekDay(TimeUtils.getNowDate()).getTime());
        datePickerDialog.getDatePicker().setMinDate(TimeUtils.GetLastWeekDay(TimeUtils.getNowDate()).getTime());
        datePickerDialog.show();
    }

    /**
     * 后一天
     */
    @OnClick(R.id.tv_tomorrow)
    void choseTomorrowDate() {
        long d = TimeUtils.dateDiff(TimeUtils.dateToStr(TimeUtils.getNowDate()),TimeUtils.dateToStr(TimeUtils.getTomorrowDay(choseDate)));
        if(d >-8 & d < 8)
            haveChoseDate(TimeUtils.getTomorrowDay(choseDate));
        else
            showToast("查看失败,只能查看前后一周内的任务");
    }


    /**
     * 前一天
     */
    @OnClick(R.id.tv_yesterday)
    void choseYesterdaDate() {
        long d = TimeUtils.dateDiff(TimeUtils.dateToStr(TimeUtils.getNowDate()),TimeUtils.dateToStr(TimeUtils.getBeforeDay(choseDate)));
        if(d >-8 & d < 8)
            haveChoseDate(TimeUtils.getBeforeDay(choseDate));
        else
            showToast("查看失败,只能查看前后一周内的任务");
    }

    /**
     * 选择日期完毕
     */
    private void haveChoseDate(Date date) {
        choseDate = date;
        getByDate(choseDate);
    }

    /**
     * 保存数据到本地
     * */
    private void SaveDataToDao( List<TaskListFragment> list){
        int num = 0;
        Gson gson = new Gson();
        TaskBodyEntity tb ;
        for(TaskListFragment l : list){
           try {
               tb = taskBodyDao.getById(num);
               if(tb != null)
                   taskBodyDao.delete(tb);
           }catch (Exception e){

           }
           String d = gson.toJson(l.datas);
           taskBodyDao.insert(new TaskBodyEntity(num,user.getUserId(),d));
           Log.i("保存任务列表",num+"");
           num++;
        }
    }

    private Integer doId;
    private Boolean doIsHaveFromLocal;

    //执行按钮回调
    @Recipient(tag = "DoTaskCallBack")
    public void DoTaskCallBack(Integer id, Boolean isHaveFromLocal, Boolean isLock, boolean idDanger, boolean isFinsh){
        doId = id;
       // doIsHaveFromLocal = isHaveFromLocal;
        doIsHaveFromLocal = NetWorkUtils.isNetworkConnected(this);
        if(isLock)
            rightClick();
        else{
            if(idDanger){
                HiddenDangerActivity__JumpCenter
                        .builder(this)
                        .setDangerId(id)
                        .setIsFinish(isFinsh)
                        .create()
                        .go();
            }else{
                TaskExecuteActivity__JumpCenter
                        .builder(this)
                        .setIsFromLocal(isHaveFromLocal)
                        .setIsFinish(isFinsh)
                        .setWorkPlanId(id)
                        .create()
                        .go();
            }

        }
    }

    /**
     * NFC解锁
     * */
    private void DoNfcLoackCallBack(){
        boolean isNext = false;
        for( TaskEntity list : noFinish){
            if(list.getWorkPlanId() == doId){
                isNext = true;
                list.setAppSwitch(1);
                break;
            }
        }
        if(!isNext){
            for(TaskEntity list : over){
                if(list.getWorkPlanId() == doId){
                    list.setAppSwitch(1);
                }
            }
        }
        DoTaskCallBack(doId, doIsHaveFromLocal, false,false, false);
    }

    public void TimeChoiseCallBack(String date){
        getByDate(TimeUtils.strToDate(date));
    }

    //注册监听事件
    @Override
    protected void registEvent(){
        //EventListenerManager.Instance().addEventLisener(this,"DoTaskCallBack",1,true,true,true);
        EventListenerManager.Instance().addEventLisener(this,"DoNfcLoackCallBack");
        EventListenerManager.Instance().addEventLisener(this,"TimeChoiseCallBack", "");
    }

    //移除监听事件
    @Override
    protected void removeEvent(){
        //EventListenerManager.Instance().removeEventLisener("DoTaskCallBack");
        EventListenerManager.Instance().removeEventLisener("DoNfcLoackCallBack");
        EventListenerManager.Instance().removeEventLisener("TimeChoiseCallBack");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxEventProcessor.get().unBind(this);
    }
}
